//
//  StringUtils.m
//
//  Created by jshan on 12. 6. 1..
//  Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//

#import "StringUtils.h"

@implementation StringUtils

+ (NSString *) stringToHex:(NSString *)str
{
	NSUInteger len = [str length];
	int charSize = len * sizeof(unichar);
  	unichar *chars = (unichar *)malloc(charSize);
	[str getCharacters:chars];
	
	NSMutableString *hexString = [[NSMutableString alloc] init];
	
	for(NSUInteger i = 0; i < len; i++ )
	{
		[hexString appendFormat:@"%02x", chars[i]];
	}
	free(chars);
	
	return hexString;
}

+ (NSString *) getCurrencyStringWithVal:(int)value {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSString *amount = [NSString stringWithFormat:@"%@", [numberFormatter stringFromNumber:[NSNumber numberWithInt:value]]];
    
    return amount;
}

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert alpha:(CGFloat)alpha
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString length] != 6) return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:alpha];
}



// 입력된 문자열을 분석하여 정규 표현식을 만든다.
+ (NSMutableString *)getRegularExpressionPatternWithInputString:(NSString *)inputString {
	
	// 정규 표현식
	NSMutableString *strRegularExpression = [[NSMutableString alloc] init];
	
	// 입력된 문자열을 한자한자 분석한다.
	for (int i = 0; i < [inputString length]; i++) {
		unichar convertedCharacter = [inputString characterAtIndex:i];
		
		// 자음인가? (Hangul Compatibility Jamo ㄱ-3131, ㅎ-314E)
		if (convertedCharacter >= [@"ㄱ" characterAtIndex:0] && convertedCharacter <= [@"ㅎ" characterAtIndex:0]) {
			
			// 초성테이블이 만들어져 있지 않다면 만들어준다.
			// (배열로 유니코드값 집어넣어도 되지만 직관적으로 하기위해서 NSObject로 넣어준다.)
                
				// 초성 (19개)
				NSArray *arrSoundInit = [[NSArray alloc] initWithObjects:
								@"ㄱ", @"ㄲ",
								@"ㄴ",
								@"ㄷ", @"ㄸ",
								@"ㄹ",
								@"ㅁ",
								@"ㅂ", @"ㅃ",
								@"ㅅ", @"ㅆ",
								@"ㅇ",
								@"ㅈ",
								@"ㅉ",
								@"ㅊ",
								@"ㅋ",
								@"ㅌ",
								@"ㅍ",
								@"ㅎ", nil];
			
			// 일단 문자열에서 한글자만 때온다.
			NSString *charterString = [inputString substringWithRange:NSMakeRange(i, 1)];
			
			// 초성 테이블에서 몇번째 인덱스에 있는지 찾는다.
			int soundInitIndex = 0;
			for (NSString *soundInitCharterString in arrSoundInit) {
				if ([soundInitCharterString isEqualToString:charterString]) {
					break;
				}
				soundInitIndex++;
			}
			
			// Hangul Compatibility Jamo에서 Hangul Syllables로 유니코드 값을 바꿔 정규 표현식을 만든다.(입력된 자음 + 'ㅏ' 부터 입력된자음 + 'ㅣ' + 'ㅎ'까지 범위를 잡는다.)
			[strRegularExpression appendString:[NSString stringWithFormat:@"[\\u%x-\\u%x]",
												[@"가" characterAtIndex:0] + soundInitIndex * (21 * 28),
												[@"가" characterAtIndex:0] + (soundInitIndex + 1) * (21 * 28) - 1]];
			
		} else if (convertedCharacter >= [@"가" characterAtIndex:0] && convertedCharacter <= [@"힣" characterAtIndex:0]) {	// 자음+모음(또는 자음+모음+자음)인가?
			
			convertedCharacter -= [@"가" characterAtIndex:0];
			
			if (convertedCharacter % 28 == 0) {	// 자음+모음
				
				[strRegularExpression appendString:[NSString stringWithFormat:@"[\\u%x-\\u%x]",
													convertedCharacter + [@"가" characterAtIndex:0],
													convertedCharacter + [@"가" characterAtIndex:0] + 28 - 1]];
				
			} else {							// 자음+모음+자음
				
				[strRegularExpression appendString:[NSString stringWithFormat:@"\\u%x",
													convertedCharacter + [@"가" characterAtIndex:0]]];
			}
			
		} else {
			[strRegularExpression appendString:[inputString substringWithRange:NSMakeRange(i, 1)]];
		}
	}
	
//	NSLog(@"%@", strRegularExpression);
	
	return strRegularExpression;
	
}

// 입력된 문자열을 입력된 정규 표현식으로 매치를 시켜 매치결과가 있으면 YES, 매치결과가 없으면 NO를 반환한다.
+ (BOOL)hasMatchInString:(NSString *)aString rexString:(NSString *)aRexString {
	
	NSError *error   = nil;
	NSRegularExpression *regexp =
	[NSRegularExpression regularExpressionWithPattern:aRexString
											  options:0
												error:&error];
	if (error != nil) {
		NSLog(@"%@", error);
	} else {
		NSTextCheckingResult *match = [regexp firstMatchInString:aString options:0 range:NSMakeRange(0, aString.length)];
		
		if (match.numberOfRanges > 0) {
			return YES;
		}
		
	}
	
	return NO;
}



// 입력된 URL을 비교하여 GNB영역을 Hidden 해야 하는지 여부를 
+ (BOOL)hasGNBHiddenString:(NSString *)hiddenUrl{
	
	if([self isURL:hiddenUrl sameUrl:@"createCafeView"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"cafeId="]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"mapView"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"mapList"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"createCafeComplete"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"jsyMemberChildList"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"facebook"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"twitter"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"sendMsgView"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"sendMessage"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"contentReportView"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"myReceiveMessage"]){
        return YES;
    }else if([self isURL:hiddenUrl sameUrl:@"tempImageConduct"]){
        return YES;
    }
    
    
	return NO;
}


+(BOOL) isURL:(NSString*)urlString sameUrl:(NSString*)sameUrl{
    NSRange range;
    range = [urlString rangeOfString:sameUrl];
    if (range.location != NSNotFound) {
        return YES;
    }
    return NO;
}

@end
